import service from '../../api/index.js'
import {
  SET_TOKEN,
  LOGOUT,
  SET_MAIN_SHOP,
  SET_SHOP,
  SET_SHOP_LIST,
  SET_ACTIVE_SHOP_ID,
  UPDATE_SHOP,
  ASYNC_LOCAL_TO_STORE,
  ONLY_LAYOUT
} from './mutation_types.js'
import {
  setToken,
  clearToken,
  setActiveShopId,
  getActiveShopId,
  getToken
} from '../../utils/auth.js'
import { getPhoneCode } from '../../api/common.js'

const user = {
  state: {
    token: "",
    expire: "",
    userInfo: {},
    shopList: [],
    mainShop: {},
    shop: {},
    activeShopId: '',
  },
  mutations: {
    // 同步本地到vuex中
    [ASYNC_LOCAL_TO_STORE]: (state) => {
      let token = getToken()
      let activeShopId = getActiveShopId()
      state.token = token
      state.activeShopId = activeShopId
    },
    [SET_TOKEN]: (state, token) => {
      state.token = token
      setToken(token)
    },
    // 登出并清除所有缓存信息
    [LOGOUT]: (state) => {
      state.token = ""
      state.activeShopId = ""
      state.shopList = []
      state.mainShop = {}
      state.userInfo = {}
      state.shop = {}
      uni.clearStorageSync();
    },
    // 仅登出不清除缓存信息
    [ONLY_LAYOUT]: (state) => {
      state.token = ""
      state.activeShopId = ""
      state.shopList = []
      state.mainShop = {}
      state.userInfo = {}
      state.shop = {}
      clearToken()
    },
    [SET_SHOP_LIST]: (state, list) => {
      state.shopList = list
    },
    [SET_ACTIVE_SHOP_ID]: (state, id) => {
      setActiveShopId(id)
      state.activeShopId = id
    },
    [SET_MAIN_SHOP]: (state, data) => {
      state.mainShop = data
    },
    [SET_SHOP]: (state, data) => {
      state.shop = data
    },
    [UPDATE_SHOP]: (state, data) => {
      let shop = state.shopList.find(v => v.id == data.id)
      for (let key in data) {
        if (shop.hasOwnProperty(key)) shop[key] = data[key]
      }
    }
  },
  actions: {
    async getPhoneCode({ commit }, params) {
      try {
        let res = await service.getPhoneCode(params)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async resetPwd({ commit }, params) {
      try {
        let res = await service.resetPwd(params)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async forgetPwd({ commit }, params) {
      try {
        let res = await service.forgetPwd(params)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    login({ commit }, params) {
      return new Promise((resolve, reject) => {
		// 商户登录
		console.log(params)
        service.login(params).then(res => {
		  console.log(res.data)
		  console.log(res.data.token)
		  console.log(res.code)
		  console.log(res.code == '000000')
          if (res.code == '000000') {
			console.log(res)
            commit(SET_TOKEN, res.data.token)
			// 设置缓存信息
			uni.setStorageSync("merchantInfo", res.data.merchantInfo);
            resolve(res.data)
          } else {
            reject(res)
          }
        }).catch(Error => {
          reject(Error)
        })
      })
    },
    register({
      commit
    }, params) {
      return new Promise((resolve, reject) => {
        service.register(params).then(res => {
          if (!res.code) {
            commit(SET_TOKEN, res.data.token)
            resolve(res.data)
          } else {
            reject(res)
          }
        }).catch(Error => {
          reject(Error)
        })
      })
    },
    async getUserInfo({ commit, dispatch }) {
      try {
        let { data } = await service.getMainShop()
        return data
      } catch (e) {
        return e
      }
    },
    /**
     * 退出登录
     * */
    async logout({ commit, dispatch }) {
      // dispatch('closeSocket')
      commit(LOGOUT)
      return true
    },
    async getMainShop({ commit }) {
      let { data } = await service.getMainShop()
      commit(SET_MAIN_SHOP, data)
      return data
    },
    async getShops({ commit, dispatch, state }) {
      try {
        let { data } = await service.getShops()
        commit(SET_SHOP_LIST, data.rows)
        if (!state.activeShopId) {
          commit(SET_ACTIVE_SHOP_ID, data.rows[0] && data.rows[0].id || null)
        }
        dispatch('initSocket')
        return data
      } catch (e) {
        //TODO handle the exception
        return e
      }
    },
    async getShop({ commit }, id) {
      let { data } = await service.getShop(id)
      return data
    },
    // 修改店铺信息
    async putShop({ getters, commit }, config) {
      let { shopId, params } = config
      let id = shopId || getters.shopId
      let res = await service.putShop(id, params)
      if (!res.code) commit(UPDATE_SHOP, { id: id, ...params })
      return res
    }
  }
}

export default user
